<!DOCTYPE html>
<!--
Copyright (c) 2016 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/settings.html">
<link rel="import" href="/tracing/ui/base/dom_helpers.html">
<link rel="import" href="/tracing/ui/base/ui.html">

<dom-module id='tr-ui-b-checkbox'>
  <template>
    <style>
    .inline {
      display: inline-block;
    }
    </style>

    <input type="checkbox" id="checkbox" class="inline"/>
    <div id="label" class="inline"></div>
  </template>
</dom-module>
<script>
'use strict';

Polymer({
  is: 'tr-ui-b-checkbox',

  created() {
    this.needsInit_ = true;
    this.defaultCheckedValue_ = undefined;
    this.settingsKey_ = undefined;
    this.label_ = undefined;
    this.checked_ = false;
    this.is_ready_ = false;
  },

  ready() {
    this.is_ready_ = true;
    this.$.checkbox.addEventListener('click', function() {
      this.checked = this.$.checkbox.checked;
    }.bind(this));
    this.maybeUpdateElements_();
  },

  maybeUpdateElements_() {
    if (!this.is_ready_) return;
    this.$.label.innerText = this.label_;
    this.$.checkbox.checked = this.checked_;
  },

  get defaultCheckedValue() {
    return this.defaultCheckedValue_;
  },

  set defaultCheckedValue(defaultCheckedValue) {
    if (!this.needsInit_) {
      throw new Error('Already initialized.');
    }
    this.defaultCheckedValue_ = defaultCheckedValue;
    this.maybeInit_();
  },

  get settingsKey() {
    return this.settingsKey_;
  },

  set settingsKey(settingsKey) {
    if (!this.needsInit_) {
      throw new Error('Already initialized.');
    }
    this.settingsKey_ = settingsKey;
    this.maybeInit_();
  },

  maybeInit_() {
    if (!this.needsInit_) return;
    if (this.settingsKey_ === undefined) return;
    if (this.defaultCheckedValue_ === undefined) return;
    this.needsInit_ = false;
    this.checked = tr.b.Settings.get(
        this.settingsKey_, this.defaultCheckedValue_);
  },

  get label() {
    return this.label_;
  },

  set label(label) {
    this.label_ = label;
    this.maybeUpdateElements_();
  },

  get checked() {
    return this.checked_;
  },

  set checked(checked) {
    this.checked_ = checked;
    this.maybeUpdateElements_();
    tr.b.Settings.set(this.settingsKey_, this.checked_);
  }
});
</script>
